package cc.zy.base.hr.controller;

import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.DateUtil;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.DraftPlan;

import cc.zy.base.hr.entity.HrDept;
import cc.zy.base.hr.service.IDraftPlanService;
import cc.zy.base.hr.service.IHrDeptService;
import cc.zy.base.system.entity.Dept;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author YF
 * @time 2022/03/05 13:36:23
 */

@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class DraftPlanController extends BaseController {
    /**
     * 添加后端校验
     */
    @Resource
    private final IDraftPlanService draftPlanService;

    @Resource
    private final IHrDeptService deptService;

    /**
     * @author zhangyihao
     * 草稿主页面跳转到 新增页面
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "trainningPlanDraft/add")
    public String trainningPlanDraftAdd() {
        return FebsUtil.hrView("plan/draft/trainningPlanDraftAdd");
    }


    /**
     * @author zhangyihao
     * 草稿主页面跳转到 更新页面
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "trainningPlanDraft/Update/{id}")
    public String trainningPlanDraftUpdate(@PathVariable Integer id, Model model) {
        resolveDraftPlanModel(id, model, false);
        return FebsUtil.hrView("plan/draft/trainningPlanDraftUpdate");
    }

    /**
     * @author zhangyihao
     * 此方法负责在草稿更新时给前端响应旧的数据
     * @param id
     * @param model
     * @param transform
     */
    private void resolveDraftPlanModel(Integer id, Model model, Boolean transform) {
        DraftPlan draftPlan = draftPlanService.findById(id);
        //拿到草稿中组合的组织名称
        String deptNames = draftPlan.getOrganizationDeptNameList();
        String[] deptNamesList = deptNames.split(";");
        //拿到当前草稿中所有组织的id
        List<HrDept> depts = deptService.findDeptsByNames(deptNamesList);
        List<Integer> deptIds = depts.stream().map(dept -> dept.getId()).collect(Collectors.toList());

        log.debug("拿到的当前草稿中的组织id有"+deptIds);

        if (draftPlan.getCreateDate() != null) {
            model.addAttribute("createDateTime", DateUtil.getDateFormat(draftPlan.getCreateDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        if (draftPlan.getLastModifyDate() != null) {
            model.addAttribute("updateDateTime", DateUtil.getDateFormat(draftPlan.getLastModifyDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        System.out.println(model);
        model.addAttribute("draftPlan", draftPlan);
        model.addAttribute("deptIds", deptIds);
    }

    /**
     * @author zhangyihao
     * 查询计划草稿的分页数据
     * @param request
     * @param draftPlan
     * @return
     */
    @GetMapping("draftPlan/list")
    @ResponseBody
    public FebsResponse draftList(QueryRequest request, DraftPlan draftPlan) {

        log.debug("前台传来的对象是：" + draftPlan);

        Map<String, Object> dataTable = getDataTable(draftPlanService.findDrafts(request, draftPlan));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 增加
     * @param draftPlan
     * @return
     */
    @PostMapping("draftPlan/add")
    @ResponseBody
    @ControllerEndpoint(operation = "新增计划草稿", exceptionMessage = "新增计划草稿异常")
    public FebsResponse addDraft(@Valid DraftPlan draftPlan) {

        draftPlan.setBatchId(1);
        draftPlan.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
        draftPlan.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());

        draftPlanService.createDraft(draftPlan);
        return new FebsResponse().success();
    }

    /**
     * 删除标签
     * @param draftIds
     * @return
     */
    @GetMapping("draftPlan/delete/{draftIds}")
    @ControllerEndpoint(operation = "删除计划草稿", exceptionMessage = "删除计划草稿异常")
    @ResponseBody
    public FebsResponse deleteColleges(@NotBlank(message = "{required}") @PathVariable String draftIds) {

        String[] ids = draftIds.split(StringPool.COMMA);
        draftPlanService.deleteDrafts(ids);
        return new FebsResponse().success();
    }


    /**
     * 更新
     * @param draftPlan
     * @return
     */
    @PostMapping("draftPlan/update")
    @ControllerEndpoint(operation = "修改计划草稿", exceptionMessage = "修改计划草稿异常")
    @ResponseBody
    public FebsResponse updateCollege(@Valid DraftPlan draftPlan) {

        log.debug("修改计划草稿id：" + draftPlan.getId());

        if (draftPlan.getId() == null) {
            throw new FebsException("计划草稿ID为空");
        }

        draftPlan.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());
        draftPlanService.updateDraft(draftPlan);
        return new FebsResponse().success();
    }

    /**
     * 计划草稿根据查询条件导出
     * @param response
     * @param draftPlan
     */
    @GetMapping("draftPlan/excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, DraftPlan draftPlan) {

        log.debug(String.format("response = %s", response));
        log.debug(String.format("draftPlan = %s", draftPlan));

        List<DraftPlan> draftPlans = draftPlanService.findDraftListNotPage(draftPlan);
        ExcelKit.$Export(DraftPlan.class, response).downXlsx(draftPlans, false);
    }


    /**
     * 通过id查询
     * @param draftId
     * @return
     */
    @GetMapping("draftPlan/findById/{draftId}")
    @ResponseBody
    public FebsResponse findById(@PathVariable Integer draftId) {

        log.debug(String.format("draftId = %s", draftId));

        DraftPlan draft = draftPlanService.findById(draftId);
        return new FebsResponse().success().data(draft);
    }


    /**
     * 标签名判重
     * @param draftName
     * @return
     */
    @GetMapping("draftPlan/isRepetitive")
    @ResponseBody
    public Boolean isRepetitive(String draftName) {

        return draftPlanService.isRepetitive(draftName);

    }

}
